import React, { useState, useEffect, useRef } from "react";
import Editor from "@monaco-editor/react";
import * as monaco from "monaco-editor";
import { loader } from "@monaco-editor/react";
import { Button, Space, message, Card, Tag } from "antd";
import * as prettier from "prettier/standalone";
import * as prettierPluginEstree from "prettier/plugins/estree";
import * as prettierPluginBabel from "prettier/plugins/babel";
import { utils } from "./EdtiorTemplateFunction";

loader.config({ monaco });
interface EditorProps {
  computedStr?: string;
  onSave?: (value: string) => void;
  rawValue?: any;
  recode: any;
  extendsJson?: string;
}
const MonacoReactEditorDemo = ({
  computedStr,
  extendsJson,
  recode,
  onSave,
  rawValue,
}: EditorProps) => {
  const [code, setCode] = useState(computedStr);
  const [theme, setTheme] = useState("vs-dark");
  const [language, setLanguage] = useState("javascript");
  const [output, setOutput] = useState<string[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [executionTime, setExecutionTime] = useState<number>(0);
  const [isResizing, setIsResizing] = useState(false);
  const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const leftPanelRef = useRef<HTMLDivElement>(null);
  const rightPanelRef = useRef<HTMLDivElement>(null);
  const resizeHandleRef = useRef<HTMLDivElement>(null);
  const outputEndRef = useRef<HTMLDivElement>(null);

  // 初始化布局
  useEffect(() => {
    if (leftPanelRef.current && rightPanelRef.current) {
      leftPanelRef.current.style.width = "70%";
      rightPanelRef.current.style.width = "30%";
    }
  }, []);

  // 添加拖拽调整宽度功能
  useEffect(() => {
    const handleMouseDown = (e: MouseEvent) => {
      e.preventDefault();
      setIsResizing(true);

      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
    };

    const handleMouseMove = (e: MouseEvent) => {
      if (
        !isResizing ||
        !containerRef.current ||
        !leftPanelRef.current ||
        !rightPanelRef.current
      )
        return;

      const containerRect = containerRef.current.getBoundingClientRect();
      const newLeftWidth =
        ((e.clientX - containerRect.left) / containerRect.width) * 100;

      // 限制最小宽度
      if (newLeftWidth >= 20 && newLeftWidth <= 80) {
        leftPanelRef.current.style.width = `${newLeftWidth}%`;
        rightPanelRef.current.style.width = `${100 - newLeftWidth}%`;

        // 重新布局编辑器
        if (editorRef.current) {
          setTimeout(() => {
            editorRef.current?.layout();
          }, 0);
        }
      }
    };

    const handleMouseUp = () => {
      setIsResizing(false);
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };

    const resizeHandle = resizeHandleRef.current;
    if (resizeHandle) {
      resizeHandle.addEventListener("mousedown", handleMouseDown);
    }

    return () => {
      if (resizeHandle) {
        resizeHandle.removeEventListener("mousedown", handleMouseDown);
      }
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };
  }, [isResizing]);

  // 语言到 Prettier parser 的映射
  const languageParserMap = {
    javascript: "babel",
    typescript: "babel",
    html: "html",
    css: "css",
    less: "css",
    scss: "css",
  };

  // 滚动到输出底部
  const scrollToBottom = () => {
    outputEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const save = async () => {
    let res = await executeCode();
    if (res) {
      let codeSmall = code?.replace(/[\r\n]+/g, "") || "";
      if (codeSmall == "") return message.error("请输入计算代码");
      onSave?.(codeSmall);
    }
  };

  // 执行 JavaScript 代码
  const executeCode = async () => {
    if (!editorRef.current) return;

    setIsRunning(true);
    setOutput([]);
    setExecutionTime(0);

    const startTime = performance.now();

    try {
      let codeToExecute = editorRef.current.getValue();

      // 创建安全执行环境
      const consoleOutput: string[] = [];
      const originalConsoleLog = console.log;
      const originalConsoleError = console.error;
      const originalConsoleWarn = console.warn;

      // 重写 console 方法以捕获输出
      console.log = (...args) => {
        const message = args
          .map((arg) =>
            typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
          )
          .join(" ");
        consoleOutput.push(`LOG: ${message}`);
        originalConsoleLog.apply(console, args);
      };

      console.error = (...args) => {
        const message = args
          .map((arg) =>
            typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
          )
          .join(" ");
        consoleOutput.push(`ERROR: ${message}`);
        originalConsoleError.apply(console, args);
      };

      console.warn = (...args) => {
        const message = args
          .map((arg) =>
            typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
          )
          .join(" ");
        consoleOutput.push(`WARN: ${message}`);
        originalConsoleWarn.apply(console, args);
      };

      // return toSql({
      //   tableName: "device_accumulate",
      //   values: [
      //     {
      //       register_address: address,
      //       time: "",
      //       value: rawValue,
      //       name: "累计用电量",
      //     },
      //   ],
      // });
      //

      // 使用 Function 构造函数创建执行环境
      const executeInSandbox = new Function(`
        "use strict";
        try {
          const result = (function() {
            let address='${recode.registerOffset}';
            let rawValue = '${rawValue}' || 0
            let extendsJson = JSON.stringify(${extendsJson}) || {}
            ${codeToExecute}
          })();

          if (result !== undefined) {
            if (typeof result === 'object' && result !== null) {
              return JSON.stringify(result, null, 2);
            }
            return String(result);
          }
          return undefined;
        } catch (error) {
          throw error;
        }
      `);

      // 执行代码
      const returnValue = executeInSandbox();

      // 恢复原始 console 方法
      console.log = originalConsoleLog;
      console.error = originalConsoleError;
      console.warn = originalConsoleWarn;

      // 处理输出
      if (returnValue !== undefined) {
        consoleOutput.push(`RETURN: ${returnValue}`);
      }

      setOutput(consoleOutput);
      message.success("代码执行成功");
      return true;
    } catch (error: any) {
      setOutput([`执行错误: ${error.message}`]);
      message.error("代码执行失败");
      return false;
    } finally {
      const endTime = performance.now();
      setExecutionTime(endTime - startTime);
      setIsRunning(false);
    }
  };

  // 格式化代码的函数
  const formatCode = async (
    codeText: string,
    lang: keyof typeof languageParserMap = "javascript"
  ) => {
    try {
      const parserType = languageParserMap[lang] || "babel";

      const formatted = await prettier.format(codeText, {
        parser: parserType,
        plugins: [prettierPluginBabel, prettierPluginEstree],
        semi: true,
        singleQuote: false,
        trailingComma: "es5",
        printWidth: 80,
        tabWidth: 2,
        useTabs: false,
      });

      return formatted;
    } catch (error: unknown) {
      if (error instanceof Error) {
        console.error("格式化错误:", error);
        message.error(`格式化失败: ${error.message}`);
      } else {
        console.error("未知格式化错误:", error);
        message.error("格式化失败: 未知错误");
      }
      return codeText;
    }
  };

  // 注册格式化提供器
  useEffect(() => {
    const registerFormattingProvider = () => {
      const formattingEditProvider = {
        async provideDocumentFormattingEdits(model: any) {
          const text = model.getValue();
          try {
            const formattedText = await formatCode(text, model.getLanguageId());
            return [
              {
                range: model.getFullModelRange(),
                text: formattedText,
              },
            ];
          } catch (error) {
            return [];
          }
        },
      };

      ["javascript", "typescript", "html", "css", "less", "scss"].forEach(
        (lang) => {
          monaco.languages.registerDocumentFormattingEditProvider(
            lang,
            formattingEditProvider
          );
        }
      );
    };

    registerFormattingProvider();
  }, []);

  const handleEditorChange = (value: any) => {
    setCode(value);
  };

  const handleEditorDidMount = (editor: any, monacoInstance: any) => {
    editorRef.current = editor;
    editor.focus();
  };

  // 格式化按钮点击处理
  const handleFormatClick = async () => {
    if (!editorRef.current) return;

    try {
      const model = editorRef.current.getModel();
      if (!model) {
        message.error("无法获取编辑器模型");
        return;
      }

      const currentText = model.getValue();
      const formattedText = await formatCode(
        currentText,
        language as keyof typeof languageParserMap
      );

      editorRef.current.executeEdits("format-source", [
        {
          range: model.getFullModelRange(),
          text: formattedText,
        },
      ]);

      // message.success("代码已格式化");
    } catch (error) {
      message.error("格式化失败");
    }
  };

  // 清空代码
  const handleClearClick = () => {
    setCode("// 代码已清空\n");
    setOutput([]);
    message.info("编辑器已清空");
  };

  // 清空输出
  const handleClearOutput = () => {
    setOutput([]);
    message.info("输出已清空");
  };

  useEffect(() => {
    monaco.editor.defineTheme("my-custom-theme", {
      base: "vs-dark",
      inherit: true,
      rules: [
        { token: "comment", foreground: "ffa500", fontStyle: "italic" },
        { token: "keyword", foreground: "569cd6" },
        { token: "string", foreground: "ce9178" },
      ],
      colors: {
        "editor.background": "#1e1e1e",
        "editor.foreground": "#d4d4d4",
      },
    });
    setTheme("my-custom-theme");
    setTimeout(() => {
      handleFormatClick();
    }, 50);
  }, []);

  return (
    <div
      ref={containerRef}
      style={{
        padding: "20px",
        height: "90vh",
        display: "flex",
        flexDirection: "column",
        backgroundColor: "#f0f2f5",
      }}
    >
      {/* 按钮控制区 */}
      <div
        style={{
          marginBottom: "16px",
          padding: "12px",
          backgroundColor: "white",
          borderRadius: "6px",
          boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
        }}
      >
        <Space>
          <Button
            type="primary"
            onClick={executeCode}
            loading={isRunning}
            disabled={isRunning}
          >
            {isRunning ? "运行中..." : "运行代码"}
          </Button>
          <Button onClick={handleFormatClick} type="default">
            格式化代码
          </Button>
          <Button onClick={handleClearClick} danger>
            清空代码
          </Button>
          {output.length > 0 && (
            <Button onClick={handleClearOutput} type="dashed">
              清空输出
            </Button>
          )}
          <Button onClick={save} color="green">
            保存
          </Button>
          <Tag color={rawValue == "error" ? "error" : "success"}>
            {rawValue == "error" && "未获取到"}原始值:rawValue----:{rawValue}
            ,地址address:{recode?.registerOffset}
          </Tag>
          <Tag color="success">拓展值:extendsJson</Tag>
        </Space>
      </div>

      {/* 编辑器和输出区域 */}
      <div
        style={{
          flex: 1,
          display: "flex",
          position: "relative",
          backgroundColor: "white",
          borderRadius: "6px",
          overflow: "hidden",
          boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
        }}
      >
        {/* 左侧代码编辑器 (70%) */}
        <div
          ref={leftPanelRef}
          style={{
            height: "100%",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <Editor
            height="100%"
            defaultLanguage="javascript"
            language={language}
            value={code}
            theme={theme}
            onChange={handleEditorChange}
            onMount={handleEditorDidMount}
            options={{
              selectOnLineNumbers: true,
              roundedSelection: false,
              readOnly: false,
              cursorStyle: "line",
              automaticLayout: true,
              minimap: { enabled: true },
              fontSize: 14,
              scrollBeyondLastLine: false,
              wordWrap: "on",
              formatOnPaste: true,
              formatOnType: true,
            }}
          />
        </div>

        {/* 拖拽手柄 */}
        <div
          ref={resizeHandleRef}
          style={{
            width: "8px",
            height: "100%",
            backgroundColor: isResizing ? "#1890ff" : "#ddd",
            cursor: "col-resize",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            position: "relative",
            zIndex: 10,
            transition: "background-color 0.2s",
          }}
          onMouseEnter={() => {
            if (!isResizing && resizeHandleRef.current) {
              resizeHandleRef.current.style.backgroundColor = "#ccc";
            }
          }}
          onMouseLeave={() => {
            if (!isResizing && resizeHandleRef.current) {
              resizeHandleRef.current.style.backgroundColor = "#ddd";
            }
          }}
        >
          <div
            style={{
              width: "2px",
              height: "20px",
              backgroundColor: isResizing ? "#fff" : "#999",
              borderRadius: "1px",
            }}
          />
        </div>

        {/* 右侧输出区域 (30%) */}
        <div
          ref={rightPanelRef}
          style={{
            height: "100%",
            display: "flex",
            flexDirection: "column",
            overflow: "hidden",
            backgroundColor: "#fafafa",
          }}
        >
          <div
            style={{
              padding: "12px",
              borderBottom: "1px solid #666666",
              fontWeight: "bold",
              fontSize: "14px",
              backgroundColor: "#1e1e1e",
              color: "#fff",
            }}
          >
            运行结果{" "}
            {executionTime > 0 && `(耗时: ${executionTime.toFixed(2)}ms)`}
          </div>

          <div
            style={{
              flex: 1,
              padding: "12px",
              overflow: "auto",
              fontFamily: "monospace",
              fontSize: "13px",
              lineHeight: "1.4",
              backgroundColor: "#1e1e1e",
              color: "#d4d4d4",
            }}
          >
            {output.length > 0 ? (
              output.map((line, index) => (
                <div
                  key={index}
                  style={{
                    whiteSpace: "pre-wrap",
                    marginBottom: "6px",
                    padding: "2px 0",
                    color: line.startsWith("ERROR:")
                      ? "#ff4d4f"
                      : line.startsWith("WARN:")
                        ? "#faad14"
                        : line.startsWith("RETURN:")
                          ? "#52c41a"
                          : "#d4d4d4",
                    borderBottom:
                      index < output.length - 1 ? "1px solid #f0f0f0" : "none",
                  }}
                >
                  {line}
                </div>
              ))
            ) : (
              <div
                style={{
                  color: "#999",
                  textAlign: "center",
                  padding: "40px 20px",
                  fontStyle: "italic",
                }}
              >
                运行代码后查看结果
              </div>
            )}
            <div ref={outputEndRef} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default MonacoReactEditorDemo;
